import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Form, Input, Upload, Select, Button, message } from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';
import axios from 'axios'
const FormItem = Form.Item;
const { Option } = Select;


@connect(({ user }) => ({
  currentUser: user.currentUser,
}))
@Form.create()
class BindingView extends Component {
  constructor() {
    super();
    this.state = {
      phone: false
    };
  }

  componentDidMount() {
    // this.saveMessage()
    const { dispatch, currentUser } = this.props;
    if (currentUser.phone === '') {
      this.setState(() => ({
        phone: true
      }))
    }
    console.log(currentUser)
  }

  checkStatus=(status)=>{
    if (status === 401) {
      localStorage.clear();
      window.g_app._store.dispatch({
        type: 'login/logout',
      });
      return;
    }
    // environment should not be used
    if (status === 403) {
      router.push('/exception/403');
      return;
    }
    if (status <= 504 && status >= 500) {
      router.push('/exception/500');
      return;
    }
    if (status >= 404 && status < 422) {
      router.push('/exception/404');
    }
  };

  // componentWillReceiveProps(nextProps,nextContext){
  //   console.log(nextProps)
  //   if(nextProps.closes==undefined){
  //     console.log('1')
  //   }
  // }

  getViewDom = ref => {
    this.view = ref;
  };

  saveMessage = () => {
    let userInfo = this.props.form.getFieldsValue();
    var reg =/^(((?=.*[A-Za-z])(?=.*\d))|((?=.*[A-Za-z])(?=.*[~!@#$%^&*()_<>]))|((?=.*\d)(?=.*[~!@#$%^&*()_<>])))[A-Za-z\d~!@#$%^&*()_<>]{8,16}$/g;

    this.props.form.validateFields((err, values) => {
      if (!err) {
        // if(!reg.test(values.addPassword)){
        //   return message.error('密码不符合要求，密码支持8-16位大小写字母、数字以及~！@#$%^&*()_<>')
        // }


        const { dispatch, currentUser } = this.props;
        // this.reqRef = requestAnimationFrame(() => {
        //   dispatch({
        //     type: 'geographic/fetcd',
        //     payload: { password:userInfo.atPassword,newPassword:userInfo.addPassword,repeatPassword:userInfo.repPassword },
        //     callback: res => {
        //       console.log('修改密码', res);
        //       if (res.code === 0) {
        //         message.success(`${res.msg}`)
        //       }
        //     },
        //   });
        // });
        const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId")) ;
    const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token ;
    const headData = {"Content-Type":"application/json","token":token,"robotId":robotId};
    return new Promise((resolve ) => {
      axios.post('/cloud/user/updatePassword',{password:window.btoa(userInfo.atPassword),newPassword:window.btoa(userInfo.addPassword),repeatPassword:window.btoa(userInfo.repPassword) },{headers:headData}).then((res) => {
         if (res.data.code === 0) {
          message.success(`${res.data.msg}`)
         }else{
          message.error(`${res.data.msg}`)
         }
      })
    })
      }
    })
  }

  reset=()=>{
    this.props.form.resetFields();

  };


  checkField(rule, value, callback){
    let reg =/^(((?=.*[A-Za-z])(?=.*\d))|((?=.*[A-Za-z])(?=.*[~!@#$%^&*()_<>]))|((?=.*\d)(?=.*[~!@#$%^&*()_<>])))[A-Za-z\d~!@#$%^&*()_<>]{8,16}$/g;
    if(value){
      if(reg.test(value))
      {
          callback()
      }else{
        callback('密码不符合要求，密码支持8-16位大小写字母、数字以及~！@#$%^&*()_<>')
      }
    }else{
      callback('')
    }
  };

  render() {
    const { currentUser } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <div className={styles.backgroundp}>
        {/* {currentUser.phone ?<p>亲爱的用户，系统检测到您已经绑定手机，为了您的账号安全，请勿将密码泄露给其他人</p>: <p>亲爱的用户，系统检测到您还没有绑定手机，为了您的账号安全，建议绑定手机</p>} */}
        <div className={styles.baseView} ref={this.getViewDom}>
          <div className={styles.left}>
            <Form className="zdyfroma" layout="vertical" onSubmit={this.handleSubmit} hideRequiredMark>
            <FormItem label='用户账号'>
                {getFieldDecorator('name', {
                    initialValue:currentUser.uid ,
                })( <Input placeholder="" />)}
              </FormItem>
              <FormItem label='当前密码'>
                {getFieldDecorator('atPassword', {
                  rules: [
                    {
                      required: true,
                      message: '当前密码为空'
                    },
                  ],
                })( <Input.Password placeholder="" />)}
              </FormItem>
              <FormItem  label='新的密码'>
                {getFieldDecorator('addPassword', {
                  rules: [
                    {
                      required: true,
                      message: '新密码为空'
                    },{
                      validator: this.checkField,
                    }
                  ],
                })(
                  <Input.Password placeholder="" />
                    // <Input type='password' allowClear />
                )}
              </FormItem>
              {
                this.state.phone ? null : <FormItem label='重复新密码'>
                  {getFieldDecorator('repPassword', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '重复新密码为空'
                      },
                      {
                        validator: this.checkField,
                      }
                    ],
                  })( <Input.Password placeholder="" />)}
                </FormItem>
              }
              {/* <Button type="primary" onClick={this.saveMessage}>修改密码</Button> */}
              {/* <Button style={{ marginLeft: 10 }} onClick={this.reset}>重置</Button> */}
              <div className={styles.flexcen}>
                <div>
                  {/*<img onClick={this.reset} src={qxbuttom} style={{ marginRight: 50 }} />*/}
                  <img onClick={this.saveMessage} src={qdbuttom} />
                </div>
              </div>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}

export default BindingView;
